#include "../../include/others/moreform.h"

void more_form()
{
    char c;
    int length; //课程时间长度
    printf("length:");
    scanf("%d", &length);

    int sober; //被叫醒后持续清醒时间
    printf("sober:");
    scanf("%d", &sober);

    printf("formula:\n"); //每分钟公式数量
    int *form = malloc(sizeof(int) * length);
    for (int i = 0; i < length; i++)
    {
        c = input_num(form + i);
    }
    if (c != '\n')
    {
        clean_io_buff();
    }

    printf("type:\n"); //每分钟的听课状态
    int *type = malloc(sizeof(int) * length);
    for (int i = 0; i < length; i++)
    {
        c = input_num(type + i);
    }
    if (c != '\n')
    {
        clean_io_buff();
    }

    printf("max formula number: %d\n", form_num(form, type, length, sober));

    free(form);
    free(type);
}

int form_num(int *form, int *type, int length, int sober)
{
    if (sober > length)
    {
        return -1;
    }
    int num = 0;
    int miss_num = 0; //每一个随眠时段错过的公式数
    int last_p = 0;   //每一个随眠时段上一个时间点的位置
    int miss_max = 0; //最大错过数
    for (int i = 0; i < length; i++)
    {
        if (*(type + i) == 1) //清醒时
        {
            num += *(form + i); //记录正常记录公式的个数
        }
        else if (*(type + i) == 0) //睡眠时
        {
            miss_num += *(form + i); //记录睡眠时段错过的公式数量
            if (i >= sober - 1)      //睡眠时段末尾
            {
                if (i > sober - 1) //去除上一个错过的时间点
                {
                    miss_num -= *(type + last_p) == 0 ? *(form + last_p) : 0;
                }
                miss_max = miss_num > miss_max ? miss_num : miss_max; //记录最大错过时间段
            }
        }
        else
        {
            return -1;
        }
        if (i > sober - 1) //开始更新上一个时间点位置
        {
            last_p++;
        }
    }
    return num + miss_max;
}